package demo.huodongbaoming.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

import java.time.Duration;

/**
 * RestTemplate配置类
 */
@Configuration
public class RestTemplateConfig {

    /**
     * 创建一个具有负载均衡能力的RestTemplate
     * 使用@LoadBalanced注解，启用自动负载均衡
     * 使用@Primary注解，确保优先注入这个Bean
     */
    @Bean
    @LoadBalanced
    @Primary
    public RestTemplate restTemplate() {
        RestTemplateBuilder builder = new RestTemplateBuilder();
        RestTemplate template = builder
            .setConnectTimeout(Duration.ofMillis(5000))
            .setReadTimeout(Duration.ofMillis(5000))
            .build();
        
        // 设置请求工厂，增加连接超时和读取超时
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectTimeout(5000);
        requestFactory.setReadTimeout(5000);
        requestFactory.setConnectionRequestTimeout(5000);
        template.setRequestFactory(requestFactory);
        
        return template;
    }
    
    /**
     * 创建一个普通的RestTemplate，不具备负载均衡能力
     * 用于直接访问具体的URL
     */
    @Bean(name = "normalRestTemplate")
    public RestTemplate normalRestTemplate() {
        RestTemplateBuilder builder = new RestTemplateBuilder();
        RestTemplate template = builder
            .setConnectTimeout(Duration.ofMillis(3000))
            .setReadTimeout(Duration.ofMillis(3000))
            .build();
        
        return template;
    }
} 